<template>
  <div class="contacts-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>联系人管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增联系人
          </el-button>
        </div>
      </template>
            <!-- 筛选区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="名称">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入联系人名称" 
              clearable 
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input 
              v-model="searchForm.tgLink" 
              placeholder="请输入联系方式" 
              clearable 
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="渠道名称">
            <el-input 
              v-model="searchForm.channelName" 
              placeholder="请输入渠道名称" 
              clearable 
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="contactsList.records"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="id" label="ID" width="80" align="left">
            <template #default="{ row }">
              <span class="id-cell">{{ row.id }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="name" label="名称" min-width="150" align="left">
            <template #default="{ row }">
              <div class="name-cell">
                <el-tooltip 
                  :content="row.name || '-'" 
                  placement="top"
                  :disabled="!row.name || row.name.length <= 30"
                >
                  <span>{{ row.name || '-' }}</span>
                </el-tooltip>
      </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="tgLink" label="联系方式" min-width="200" align="left">
            <template #default="{ row }">
              <span class="link-cell">{{ row.tgLink }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="channelName" label="渠道名称" min-width="120" align="center">
            <template #default="{ row }">
              <span>{{ row.channelName || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="countryName" label="国家" min-width="150" align="center">
            <template #default="{ row }">
              <div class="region-cell">
                <el-tooltip 
                  :content="row.countryName || '-'" 
                  placement="top"
                  :disabled="!row.countryName"
                >
                  <span>{{ row.countryName || '-' }}</span>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="isDisplay" label="是否显示" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isDisplay === 1 || row.isDisplay === true ? 'success' : 'danger'">
                {{ row.isDisplay === 1 || row.isDisplay === true ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createAt" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              <span>{{ row.createAt || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <div class="operation-buttons">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[50,100,500,1000]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="contactsList.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增联系人弹框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增联系人"
      width="420px"
      :before-close="handleCloseAdd"
      center
      align-center
      :modal="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="custom-dialog"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            class="edit-form-input"
            v-model="addForm.name"
            placeholder="请输入联系人名称"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item class="edit-form-item" label="联系方式" prop="tgLink">
          <el-input
            class="edit-form-input"
            v-model="addForm.tgLink"
            placeholder="https://t.me/username"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <div class="form-tip">
            格式示例：https://t.me/username
          </div>
        <el-form-item label="渠道" prop="channelId">
          <el-select
            v-model="addForm.channelId"
            placeholder="请选择渠道"
            style="width: 100%"
            clearable
          >
            <el-option 
              v-for="channel in channelList"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="洲" prop="continent" class="continent-form-item">
          <div class="continent-select-group">
            <el-select 
              v-model="addForm.continent" 
              placeholder="请先选择洲" 
              class="continent-select"
              clearable
              @change="handleContinentChange('add')"
            >
              <el-option 
                v-for="continent in continentList" 
                :key="continent.value" 
                :label="continent.label" 
                :value="continent.value"
              />
            </el-select>
            <el-button
              type="primary"
              size="small"
              plain
              class="select-all-btn"
              @click="handleSelectAllCountries('add')"
              :disabled="!addForm.continent || !filteredRegionList.length"
            >
              全选国家
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="国家" prop="region">
          <el-select 
            v-model="addForm.region" 
            placeholder="请先选择洲，再选择区域" 
            style="width: 100%" 
            multiple
            :disabled="!addForm.continent"
          >
            <el-option 
              v-for="item in filteredRegionList" 
              :key="item.id" 
              :label="item.country" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="display-group" label="是否显示" prop="isDisplay">
          <el-radio-group class="radio-group" v-model="addForm.isDisplay">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="handleSaveAdd" 
            :loading="addLoading"
            :disabled="!isAddFormValid"
          >
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 编辑联系人弹框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑联系人"
      width="500px"
      :before-close="handleCloseEdit"
      center
      align-center
      :modal="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="custom-dialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
        class="edit-form"
      >
        <el-form-item class="edit-form-item" label="名称" prop="name">
          <el-input
            class="edit-form-input"
            v-model="editForm.name"
            placeholder="请输入联系人名称"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item class="edit-form-item" label="联系方式" prop="tgLink">
          <el-input
            class="edit-form-input"
            v-model="editForm.tgLink"
            placeholder="https://t.me/username"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="渠道" prop="channelId">
        <el-select
          v-model="editForm.channelId"
          placeholder="请选择渠道"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="channel in channelList"
            :key="channel.id"
            :label="channel.name"
            :value="channel.id"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="洲" prop="continent" class="continent-form-item">
          <div class="continent-select-group">
            <el-select 
              v-model="editForm.continent" 
              placeholder="请先选择洲" 
              class="continent-select"
              clearable
              @change="handleContinentChange('edit')"
            >
              <el-option 
                v-for="continent in continentList" 
                :key="continent.value" 
                :label="continent.label" 
                :value="continent.value"
              />
            </el-select>
            <el-button
              type="primary"
              size="small"
              plain
              class="select-all-btn"
              @click="handleSelectAllCountries('edit')"
              :disabled="!editForm.continent || !filteredEditRegionList.length"
            >
              全选国家
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="区域" prop="region">
          <el-select 
            v-model="editForm.region" 
            placeholder="请先选择洲，再选择区域" 
            style="width: 100%" 
            multiple
            :disabled="!editForm.continent"
          >
          <el-option 
              v-for="item in filteredEditRegionList" 
            :key="item.id" 
            :label="item.country" 
            :value="item.id"
          />
        </el-select>
      </el-form-item>
        <el-form-item class="display-group" label="是否显示" prop="isDisplay">
          <el-radio-group class="radio-group" v-model="editForm.isDisplay">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="handleSaveEdit" 
            :loading="editLoading"
            :disabled="!isEditFormValid"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllIssues, insertIssue, updateIssue, deleteIssue, getAllChannels, getAllRegionTree } from '@/api/user.js'

export default {
  name: 'Contacts',
  components: {
    Plus,
    Edit,
    Delete
  },
  setup() {
    // 弹框显示状态
    const addDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const addLoading = ref(false)
    const editLoading = ref(false)
    const addFormRef = ref()
    const editFormRef = ref()
    
    // 数据列表
    const contactsList = ref({
      records: [],
      total: 0,
      size: 50,
      current: 1,
      pages: 1
    })
    // 分页表单 - 添加分页相关参数
    const searchForm = reactive({
      page: 1,
      pageSize: 50,
      name:'',
      tgLink: '',
      channelName:''
    })
    const loading = ref(false)
    const currentEditId = ref(null)
    
    // 表单数据
    const addForm = reactive({
      tgLink: '',
      isDisplay: true,
      region: [],
      channelId: '',
      name: '',
      continent: ''
    })
    
    const editForm = reactive({
      tgLink: '',
      isDisplay: true,
      region: [],
      channelId: '',
      name: '',
      continent: ''
    })
    
    // 表单验证状态
    const isAddFormValid = computed(() => {
      // 检查联系方式是否填写且格式正确
      const tgLinkValid = addForm.tgLink
      
      // 检查是否显示是否已选择
      const isDisplayValid = addForm.isDisplay !== null && addForm.isDisplay !== undefined
      const regionValid = Array.isArray(addForm.region) && addForm.region.length > 0
      const channelValid = addForm.channelId !== '' && addForm.channelId !== null && addForm.channelId !== undefined
      const nameValid = addForm.name && addForm.name.trim() !== '' // 添加名称验证
      return tgLinkValid && isDisplayValid && regionValid && channelValid && nameValid // 添加名称验证
    })
    
    const isEditFormValid = computed(() => {
      // 检查联系方式是否填写且格式正确
      const tgLinkValid = editForm.tgLink
      
      // 检查是否显示是否已选择
      const isDisplayValid = editForm.isDisplay !== null && editForm.isDisplay !== undefined
      const regionValid = Array.isArray(editForm.region) && editForm.region.length > 0
      const channelValid = editForm.channelId !== '' && editForm.channelId !== null && editForm.channelId !== undefined
      const nameValid = editForm.name && editForm.name.trim() !== '' // 添加名称验证
      return tgLinkValid && isDisplayValid && regionValid && channelValid && nameValid // 添加名称验证
    })
    
    // 表单验证规则
    const addRules = {
      name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
      ],
      tgLink: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { 
          required: true,
          message: '格式不正确，应为：https://t.me/username', 
          trigger: 'blur' 
        }
      ],
      isDisplay: [
        { required: true, message: '请选择是否显示', trigger: 'change' }
      ],
      channelId: [
        { required: true, message: '请选择渠道', trigger: 'change' }
      ],
      continent: [
        { required: true, message: '请选择洲', trigger: 'change' }
      ],
  region: [
    { 
      required: true, 
      message: '请至少选择一个区域', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (Array.isArray(value) && value.length > 0) {
          callback()
        } else {
          callback(new Error('请至少选择一个区域'))
        }
      }
    }
  ]

    }
    
    const editRules = {
      name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
      ],
      tgLink: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { 
          required: true, 
          message: '格式不正确，应为：https://t.me/username', 
          trigger: 'blur' 
        }
      ],
      isDisplay: [
        { required: true, message: '请选择是否显示', trigger: 'change' }
      ],
        channelId: [
          { required: true, message: '请选择渠道', trigger: 'change' }
        ],
        continent: [
          { required: true, message: '请选择洲', trigger: 'change' }
      ],
        region: [
      { 
        required: true, 
        message: '请至少选择一个区域', 
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (Array.isArray(value) && value.length > 0) {
            callback()
          } else {
            callback(new Error('请至少选择一个区域'))
          }
        }
      }
    ]
    }
    
        // 搜索功能
    const handleSearch = () => {
      console.log('searchForm:', searchForm)
      searchForm.page = 1 // 搜索时重置到第一页
      loadContacts()
    }
       // 重置功能
    const handleReset = () => {
      // 清空所有筛选条件
      searchForm.name = ''
      searchForm.tgLink = ''
      searchForm.channelName = ''
      searchForm.page = 1 // 重置到第一页
      loadContacts() // 重新加载数据
    }

    // 加载联系人数据
    const loadContacts = async () => {
      try {
        loading.value = true
          // 传递分页参数
          const response = await getAllIssues({
            pageNum: searchForm.page,
            pageSize: searchForm.pageSize,
            name: searchForm.name,
            tgLink: searchForm.tgLink,
            channelName: searchForm.channelName
          })
        ////console.log('联系人数据响应:', response)
        
        // 检查响应格式
          if (response && response.records) {
            // 如果是分页对象格式
            contactsList.value = {
              ...response,
              records: Array.isArray(response.records) ? [...response.records] : []
            }
          } else if (Array.isArray(response)) {
            // 兼容直接返回数组的格式
            contactsList.value = {
              records: response,
              total: response.length,
              size: searchForm.pageSize,
              current: searchForm.page,
              pages: Math.ceil(response.length / searchForm.pageSize)
            }
        } else if (response && response.code === 0) {
          // 兼容标准响应格式
          const dataList = response.data || []
          contactsList.value = {
            records: dataList,
            total: dataList.length,
            size: searchForm.pageSize,
            current: searchForm.page,
            pages: dataList.length ? Math.ceil(dataList.length / searchForm.pageSize) : 1
          }
        } else {
          ElMessage.error((response && response.message) || '获取联系人数据失败')
        }

      } catch (error) {
        //console.error('Load contacts error:', error)
        ElMessage.error('获取联系人数据失败')
        // 出错时设置空数据
        contactsList.value = {
          records: [],
          total: 0,
          size: 50,
          current: 1,
          pages: 1
        }
      } finally {
        loading.value = false
      }
    }

      // 分页大小变化处理
      const handleSizeChange = (size) => {
        searchForm.pageSize = size
        loadContacts()
      }

      // 当前页码变化处理
      const handleCurrentChange = (current) => {
        searchForm.page = current
        loadContacts()
    }
    
    // 打开新增弹框
    const handleAdd = () => {
      if (channelList.value.length === 0) {
        loadChannelList()
      }
      addDialogVisible.value = true
      // 重置表单
      addForm.tgLink = ''
      addForm.name = ''
      addForm.isDisplay = true
      addForm.channelId = ''
      addForm.continent = ''
      addForm.region = []
    }
    
    // 关闭新增弹框
    const handleCloseAdd = () => {
      addDialogVisible.value = false
      addFormRef.value?.resetFields()
      addForm.continent = ''
      addForm.region = []
    }
    

const handleEdit = (row) => {
  const populateEditForm = () => {
      if (row.region && typeof row.region === 'string') {
      editForm.region = row.region
        .split(',')
        .map(id => {
          const trimmed = id.trim()
          const numericId = parseInt(trimmed, 10)
          return Number.isNaN(numericId) ? trimmed : numericId
        })
      } else {
        editForm.region = Array.isArray(row.region) ? row.region : []
      }

    const resolveChannelId = () => {
      const candidate =
        row.channelId ??
        row.channelID ??
        (row.channel && (row.channel.id ?? row.channel.channelId))

      if (candidate === undefined || candidate === null || candidate === '') {
        return ''
      }
      const numericId = Number(candidate)
      return Number.isNaN(numericId) ? candidate : numericId
    }

    editForm.channelId = resolveChannelId()
      editForm.tgLink = row.tgLink || ''
      editForm.name = row.name || ''
      editForm.isDisplay = row.isDisplay === 1 || row.isDisplay === true
    
    // 根据已选区域反推洲
    if (editForm.region && editForm.region.length > 0) {
      // 获取第一个区域的洲
      const firstRegionId = editForm.region[0]
      const continentId = getContinentByCountryId(firstRegionId)
      if (continentId) {
        editForm.continent = continentId
  } else {
        editForm.continent = ''
      }
    } else {
      editForm.continent = ''
    }
    
    currentEditId.value = row.id
    editDialogVisible.value = true
  }

  const loaders = []
  if (regionTree.value.length === 0) {
    loaders.push(loadRegionTree())
  }
  if (channelList.value.length === 0) {
    loaders.push(loadChannelList())
  }

  if (loaders.length > 0) {
    Promise.all(loaders)
      .then(populateEditForm)
      .catch(error => {
        //console.error('加载编辑所需数据失败:', error)
        populateEditForm()
      })
  } else {
    populateEditForm()
  }
}
    
    // 关闭编辑弹框
    const handleCloseEdit = () => {
      editDialogVisible.value = false
      currentEditId.value = null
      editFormRef.value?.resetFields()
      editForm.continent = ''
      editForm.region = []
    }
    
    // 保存编辑联系人
    const handleSaveEdit = async () => {
      if (!editFormRef.value) return
      
      try {
        // 验证表单
        await editFormRef.value.validate()
        
        editLoading.value = true
        
        // 调用API
        const requestData = {
          id: currentEditId.value,
          tgLink: editForm.tgLink,
          name: editForm.name,
          channelId: editForm.channelId,
          isDisplay: editForm.isDisplay ? 1 : 0, // 转换为数字
          region: editForm.region.join(',')
        }
        
        const response = await updateIssue(requestData)
        //console.log('修改API响应：', response)
        
        if (response.code === 0 || response.code === 200) {
          ElMessage.success(response.message || response.result || '修改成功')
          editDialogVisible.value = false
          loadContacts() // 重新加载数据
        } else {
          ElMessage.error(response.message || response.result || '修改失败')
        }
      } catch (error) {
        //console.error('修改失败 error:', error)
        ElMessage.error('修改失败')
      } finally {
        editLoading.value = false
      }
    }
    
    // 删除联系人
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除联系人 "${row.tgLink}" 吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        const response = await deleteIssue(row.id)
        //console.log('删除API响应：', response)
        
        if (response.code === 0 || response.code === 200) {
          ElMessage.success(response.message || response.result || '删除成功')
          loadContacts() // 重新加载数据
        } else {
          ElMessage.error(response.message || response.result || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          //console.error('Delete contact error:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 保存新增联系人
    const handleSaveAdd = async () => {
      if (!addFormRef.value) return
      
      try {
        // 验证表单
        await addFormRef.value.validate()
        
        addLoading.value = true
        
        // 调用API
        const requestData = {
          tgLink: addForm.tgLink,
          name: addForm.name,
          channelId: addForm.channelId,
          isDisplay: addForm.isDisplay ? 1 : 0, // 转换为数字
          region: addForm.region.join(',')
        }
        
        //console.log('发送数据：', requestData)
        
        const response = await insertIssue(requestData)
        
        //console.log('API响应：', response)
        
        if (response.code === 0 || response.code === 200) {
          ElMessage.success(response.message || response.result || '新增联系人成功')
          handleCloseAdd()
          loadContacts() // 重新加载数据
        } else {
          ElMessage.error(response.message || response.result || '新增失败')
        }
      } catch (error) {
        //console.error('新增失败 error:', error)
      } finally {
        addLoading.value = false
      }
    }

  const channelList = ref([])
  const regionList = ref([]) // 保留用于显示和查找
  const regionTree = ref([]) // 树形数据
  
  // 洲列表（从树形数据生成，type=2 表示洲）
  const continentList = computed(() => {
    if (!regionTree.value || !Array.isArray(regionTree.value)) {
      return []
    }
    return regionTree.value
      .filter(item => item && item.type === 2) // 只取洲（type=2）
      .map(continent => ({
        label: continent.country, // 洲名称
        value: continent.id,      // 洲ID
        code: continent.code,     // 洲代码
        type: continent.type      // type=2
      }))
  })
  
  // 根据洲ID获取该洲下的所有国家（type=1 表示国家）
  const getCountriesByContinent = (continentId) => {
    if (!regionTree.value || !Array.isArray(regionTree.value)) {
      return []
    }
    const continent = regionTree.value.find(c => 
      c && c.type === 2 && (c.id === continentId || String(c.id) === String(continentId))
    )
    if (!continent) {
      return []
    }
    
    // 从洲的 children 中获取所有国家（type=1）
    const children = continent.children || []
    if (!Array.isArray(children)) {
      return []
    }
    return children
      .filter(item => item && item.type === 1) // 只取国家（type=1）
      .map(country => ({
        id: country.id,           // 国家ID
        country: country.country,  // 国家名称
        code: country.code,        // 国家代码
        type: country.type         // type=1
      }))
  }
  
  // 根据国家ID查找所属的洲ID
  const getContinentByCountryId = (countryId) => {
    if (!regionTree.value || !Array.isArray(regionTree.value)) {
      return null
    }
    for (const continent of regionTree.value) {
      // 只查找洲（type=2）
      if (!continent || continent.type !== 2) continue
      
      const children = continent.children || []
      if (!Array.isArray(children)) continue
      
      const country = children.find(c => 
        c && c.type === 1 && (c.id === countryId || String(c.id) === String(countryId))
      )
      if (country) {
        return continent.id
      }
    }
    return null
  }
  
  // 过滤后的区域列表（新增表单）
  const filteredRegionList = computed(() => {
    if (!addForm.continent) return []
    return getCountriesByContinent(addForm.continent)
  })
  
  // 过滤后的区域列表（编辑表单）
  const filteredEditRegionList = computed(() => {
    if (!editForm.continent) return []
    return getCountriesByContinent(editForm.continent)
  })
  
  // 洲选择变化处理
  const handleContinentChange = (type) => {
    if (type === 'add') {
      // 清空已选择的区域
      addForm.region = []
    } else {
      // 清空已选择的区域
      editForm.region = []
    }
  }

  // 全选国家
  const handleSelectAllCountries = (type) => {
    if (type === 'add') {
      addForm.region = filteredRegionList.value.map(item => item.id)
    } else {
      editForm.region = filteredEditRegionList.value.map(item => item.id)
    }
  }

  const loadChannelList = async () => {
    try {
      // 构建请求参数
      const params = {
          page: 1,
          pageSize: 10000
        }
      const response = await getAllChannels(params)
      if (response && response.records && Array.isArray(response.records)) {
        channelList.value = response.records
      } else if (response && response.code === 0 && Array.isArray(response.data)) {
        channelList.value = response.data
      } else if (Array.isArray(response)) {
        channelList.value = response
      } else {
        console.warn('获取渠道列表返回格式异常:', response)
        channelList.value = []
      }
    } catch (error) {
      //console.error('获取渠道列表失败:', error)
      ElMessage.error('获取渠道列表失败')
      channelList.value = []
    }
  }

  // 加载区域树形数据
  const loadRegionTree = async () => {
    try {
      const response = await getAllRegionTree()
      let treeData = []
      
      // 处理不同的响应格式
      if (Array.isArray(response)) {
        treeData = response
      } else if (response && response.code === 0) {
        treeData = response.data || []
      } else if (response && response.data && Array.isArray(response.data)) {
        treeData = response.data
      }
      
      // 确保 treeData 是数组
      if (!Array.isArray(treeData)) {
        treeData = []
      }
      
      regionTree.value = treeData
      //console.log('区域树形数据:', treeData)
      if (treeData.length > 0) {
        //console.log('第一个洲的数据结构:', treeData[0])
      }
      
      // 将树形数据扁平化到 regionList，用于显示和查找（只包含国家，type=1）
      const flatList = []
      treeData.forEach(continent => {
        // 只处理洲（type=2）
        if (!continent || continent.type !== 2) return
        
        const children = continent.children || []
        if (!Array.isArray(children)) return
        
        children.forEach(country => {
          // 只取国家（type=1）
          if (country && country.type === 1) {
            flatList.push({
              id: country.id,           // 国家ID
              country: country.country,  // 国家名称
              code: country.code,        // 国家代码
              type: country.type         // type=1
            })
          }
        })
      })
      regionList.value = flatList
      //console.log('扁平化后的区域列表（国家）:', flatList)
    } catch (error) {
      //console.error('获取区域树形数据失败:', error)
      ElMessage.error('获取区域数据失败')
      regionTree.value = []
      regionList.value = []
    }
  }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadContacts()
    loadRegionTree()
    loadChannelList()
    })
    
    return {
      // 状态
      searchForm,
      addDialogVisible,
      editDialogVisible,
      addLoading,
      editLoading,
      loading,
      contactsList,
      addFormRef,
      editFormRef,
      addForm,
      editForm,
      addRules,
      editRules,
      isAddFormValid,
      isEditFormValid,
      regionList,
      channelList,
      continentList,
      filteredRegionList,
      filteredEditRegionList,
      // 方法
      loadContacts,
      handleAdd,
      handleCloseAdd,
      handleSaveAdd,
      handleEdit,
      handleCloseEdit,
      handleSaveEdit,
      handleDelete,
      handleContinentChange,
      handleSizeChange,
      handleCurrentChange,
      handleSelectAllCountries,
      handleSearch,
      handleReset
    }
  }
}
</script>

<style scoped>
.contacts-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.content {
  text-align: center;
  padding: 40px;
  color: #666;
}

/* 美化表单提示样式 */
.custom-dialog .form-tip {
  font-size: 12px;
  color: #999;
  margin-left: 80px;
  margin-top: -5px;
  margin-bottom: 50px;
}

.custom-dialog .display-group {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.custom-dialog .display-group .el-form-item__content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.custom-dialog .display-group .radio-group {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 24px;
  flex: 1;
}

.custom-dialog .display-group .el-radio {
  display: flex;
  align-items: center;
  margin-right: 0;
  white-space: nowrap;
}

.custom-dialog .display-group .el-radio__label {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin-left: 8px;
}

/* 弹框样式 */
.dialog-footer {
  text-align: center;
  padding: 0;
}

.dialog-footer .el-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
}

/* 美化表单样式 */
.custom-dialog .el-form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background: transparent;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
  border: none;
  transition: all 0.3s ease;
  width: 100%; /* 确保表单项占满宽度 */
}

.custom-dialog .edit-form-input {
  margin-bottom: 0 !important;
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

/* 确保所有输入框宽度一致 - 只针对 el-input */
.custom-dialog .el-form-item__content .el-input {
  width: 100% !important;
  flex: 1 1 auto !important; /* 在 flex 容器中占满空间 */
  min-width: 0 !important; /* 允许收缩 */
  max-width: 100% !important;
  display: flex !important; /* 确保 el-input 本身也是 flex 容器 */
}

/* 下拉框保持原有布局，不受强制 flex 影响 */
.custom-dialog .el-form-item__content .el-select {
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

/* 确保渠道和国家下拉框正常显示 */
.custom-dialog .el-form-item[prop="channelId"] .el-select,
.custom-dialog .el-form-item[prop="region"] .el-select {
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

.custom-dialog .el-form-item__content .el-input__wrapper,
.custom-dialog .el-form-item__content .el-input_wrapper {
  width: 100% !important;
  flex: 1 1 auto !important;
  min-width: 0 !important;
  max-width: 100% !important;
  display: flex !important; /* 确保 wrapper 也是 flex 容器 */
}

/* 下拉框的 wrapper 保持原有布局 */
.custom-dialog .el-form-item__content .el-select__wrapper,
.custom-dialog .el-form-item__content .el-select_wrapper {
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

/* 确保输入框内部元素也占满宽度 */
.custom-dialog .el-form-item__content .el-input__inner,
.custom-dialog .el-form-item__content .el-input_inner {
  width: 100% !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

/* 针对名称和联系方式输入框的特殊处理 */
.custom-dialog .el-form-item[prop="name"] .el-form-item__content,
.custom-dialog .el-form-item[prop="tgLink"] .el-form-item__content {
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
}

.custom-dialog .el-form-item[prop="name"] .el-input,
.custom-dialog .el-form-item[prop="tgLink"] .el-input {
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

.custom-dialog .el-form-item[prop="name"] .el-input__wrapper,
.custom-dialog .el-form-item[prop="name"] .el-input_wrapper,
.custom-dialog .el-form-item[prop="tgLink"] .el-input__wrapper,
.custom-dialog .el-form-item[prop="tgLink"] .el-input_wrapper {
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

.custom-dialog .el-form-item[prop="name"] .el-input__inner,
.custom-dialog .el-form-item[prop="name"] .el-input_inner,
.custom-dialog .el-form-item[prop="tgLink"] .el-input__inner,
.custom-dialog .el-form-item[prop="tgLink"] .el-input_inner {
  width: 100% !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

.custom-dialog .el-form-item:hover {
  box-shadow: none;
  border-color: transparent;
}

.custom-dialog .el-form-item__label {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 40px;
  line-height: 40px;
  font-weight: 500;
  color: #333;
  min-width: 80px;
  padding-right: 12px;
}

.custom-dialog .el-form-item__content {
  display: flex !important;
  align-items: center;
  flex: 1 !important;
  height: 40px;
  min-width: 0 !important; /* 允许 flex 子元素收缩 */
  width: 100% !important; /* 确保内容区域占满 */
  max-width: 100% !important;
}

.custom-dialog .el-radio-group {
  display: flex;
  gap: 24px;
  align-items: center;
}

.custom-dialog .el-radio {
  margin-right: 0;
  display: flex;
  align-items: center;
  font-weight: 500;
}

.custom-dialog .el-radio__label {
  font-size: 14px;
  color: #666;
}

/* 最高优先级修复双边框 */
.custom-dialog .el-form-item :deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px !important;
  box-shadow: none !important;
  outline: none !important;
}

.custom-dialog .el-form-item :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: none !important;
}

.custom-dialog .el-form-item :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}

.custom-dialog .el-form-item :deep(.el-input__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}



/* 美化按钮样式 */
.custom-dialog .dialog-footer .el-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.custom-dialog .dialog-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.custom-dialog .dialog-footer .el-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
}

/* 自定义弹框样式 */
.custom-dialog :deep(.el-dialog) {
  margin: 0 auto !important;
  top: 10vh !important;
  transform: none !important;
  max-height: 80vh;
  overflow-y: auto;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  border: none;
}

.custom-dialog :deep(.el-dialog__header) {
  text-align: center;
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.custom-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.custom-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
}

.custom-dialog :deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.3);
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: #fafafa;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px 24px;
  background: #fafafa;
  border-radius: 0 0 12px 12px;
}

/* 美化遮罩层 */
.custom-dialog :deep(.el-overlay) {
  background-color: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4px);
}

.custom-dialog :deep(.el-dialog__wrapper) {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 10vh;
}

/* 编辑表单样式 */
.edit-form {
  padding: 20px;
}

.edit-form .el-form-item {
  margin-bottom: 20px;
}

.edit-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 编辑表单样式 - 移除输入框自定义样式 */

.edit-form .el-radio-group {
  display: flex;
  gap: 20px;
}

.edit-form .el-radio {
  margin-right: 0;
}

.edit-form .el-radio__label {
  font-size: 14px;
  color: #606266;
}
.button-group {
  display: flex;
  align-items: center;
  gap: 10px;
}
/* 表格容器 */
.table-container {
  width: 100%;
}

/* ID列样式 */
.id-cell {
  color: #909399;
  font-weight: 500;
}

/* 名称列 - 最多3行显示 */
.name-cell {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  word-break: break-word;
}

.name-cell > span {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 联系方式列 */
.link-cell {
  word-break: break-all;
}

/* 区域列样式 - 一行显示 */
.region-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.region-cell > span {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
}

.operation-buttons .el-button {
  margin: 0;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 洲选择与全选按钮布局 */
.custom-dialog .continent-form-item .el-form-item__content {
  width: 100%;
}
.custom-dialog .continent-select-group {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 12px;
}
.custom-dialog .continent-select-group .continent-select {
  flex: 0 0 80% !important; 
  max-width: 80% !important;
  width: auto !important; /* 覆盖全局宽度设置 */
  min-width: 0 !important;
}
.custom-dialog .continent-select-group .continent-select .el-select__wrapper,
.custom-dialog .continent-select-group .continent-select .el-select_wrapper {
  width: 100% !important;
  flex: none !important; /* 不参与 flex 增长 */
}
.custom-dialog .continent-select-group .select-all-btn {
  margin-left: auto; 
  height: 32px; 
  line-height: 30px; 
  padding-top: 0;
  padding-bottom: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa !important;
  padding: 15px;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px 20px;
}
.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}
.search-form .actions-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.search-form .actions-item :deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  gap: 10px;
}
.search-form :deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px !important;
  box-shadow: none !important;
  outline: none !important;
}
.search-form :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: none !important;
}
.search-form :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}
.search-form :deep(.el-input__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}
.search-form :deep(.el-select) {
  width: 180px;
}

</style>
